#!/usr/bin/perl
# 2012/11/28 Making conversion table from Hind iii information to specified resolution section

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if((@ARGV != 4 and @ARGV != 6) or $ARGV[0] eq '--help'){
	die "Usage : $0  -i [Hind III sites file] -o [conversion table] -b [bin size]\n";
}


my %opt;
getopts("i:o:b:", \%opt);
my $FILE_HINDIII = $opt{i};
my $FILE_table = $opt{o};

my $BIN_SIZE = 50000;
if(exists $opt{b}){
	$BIN_SIZE = $opt{b};
}



### read Hind III middle sites
my %Hinds;
my %MAX_chr = ('chr1'=>0, 'chr2'=>0, 'chr3'=>0);
{
	my $fh_in = IO::File->new($FILE_HINDIII) or die "cannot open $FILE_HINDIII: $!";
	while($_ = $fh_in->getline()){
		if(m/^#/){
			next;
		}
		s/\r?\n//;
		my ($number, $chr, $pos, $before, $after) = split /\t/;

		# get each chromosome size
		my $rightEdge = $pos + $after;
		if($MAX_chr{$chr} < $rightEdge){
			$MAX_chr{$chr} = $rightEdge;
		}

		my $middleL = $pos - int($before / 2);
		my $middleR = $pos + int($after / 2);

		my $nameL = $number . "L";
		my $nameR = $number . "R";
		push @{$Hinds{$chr}}, [$nameL, $middleL];
		push @{$Hinds{$chr}}, [$nameR, $middleR];
	}
	$fh_in->close();
}



### output conversion table
my $binNum = 0;
my $start = 0;
my $end = 0;
my $fh_out = IO::File->new($FILE_table, 'w') or die "cannot write $FILE_table: $!";
foreach my $chr(qw(chr1 chr2 chr3)){
	while($end < $MAX_chr{$chr}){
		$binNum++;
		$start = $end + 1;
		$end = $start + $BIN_SIZE - 1;
		if($end > $MAX_chr{$chr}){
			$end = $MAX_chr{$chr};
		}
		my @flagList;
		foreach my $k(@{$Hinds{$chr}}){
			my ($name, $middle) = @$k;
			if($start <= $middle and $middle <= $end){
				push @flagList, $name;
			}
		}
		my $binName = "bin_" . $binNum . "|" . $chr . ":" . $start . "-" . $end;
		my $values = join("\t", @flagList);
		$fh_out->print("$binName\t$values\n");
	}
	$start = 0;
	$end = 0;
}
$fh_out->close();
